package org.salatec.tapestry4e.wizard;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.dialogs.WizardNewFileCreationPage;

public class NewTMLFileWizardPage extends WizardNewFileCreationPage {

	private IContentType fContentType;

	public NewTMLFileWizardPage(String pageName, IStructuredSelection selection) {
		super(pageName, selection);
	}

	public String addDefaultExtension(String fileName) {
		StringBuffer newFileName = new StringBuffer(fileName);

		newFileName.append("."); //$NON-NLS-1$
		newFileName.append("tml");

		return newFileName.toString();
	}

	/**
	 * Get content type associated with this new file wizard
	 * 
	 * @return IContentType
	 */
	private IContentType getContentType() {
		if (fContentType == null)
			fContentType = Platform.getContentTypeManager().getContentType(
					"org.salatec.tapestry4e.tmlsource");
		return fContentType;
	}

	/**
	 * This method is overriden to set the selected folder to web contents
	 * folder if the current selection is outside the web contents folder.
	 */
	protected void initialPopulateContainerNameField() {
		super.initialPopulateContainerNameField();

		IPath fullPath = getContainerFullPath();
		IProject project = getProjectFromPath(fullPath);
		// IPath webContentPath = getWebContentPath(project);

		// if (webContentPath != null && !webContentPath.isPrefixOf(fullPath)) {
		// setContainerFullPath(webContentPath);
		// }
	}

	/**
	 * Returns the project that contains the specified path
	 * 
	 * @param path
	 *            the path which project is needed
	 * @return IProject object. If path is <code>null</code> the return value is
	 *         also <code>null</code>.
	 */
	private IProject getProjectFromPath(IPath path) {
		IWorkspace workspace = ResourcesPlugin.getWorkspace();
		IProject project = null;

		if (path != null) {
			if (workspace.validatePath(path.toString(), IResource.PROJECT)
					.isOK()) {
				project = workspace.getRoot().getProject(path.toString());
			} else {
				project = workspace.getRoot().getFile(path).getProject();
			}
		}

		return project;
	}

}
